package com.mioto.ld.utils;

import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author mioto-qinxj
 * @date 2024/7/1
 * @desc
 */
@Slf4j
@Component
public class SmsHelper {
    private final String signName = "湖南利达实业发展有限公司";
    private String accessKeyId;
    private String accessKeySecret;
    private String templateCode;
    private Client client;

    @PostConstruct
    public void init() throws Exception {
        Config config = new Config().setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "dysmsapi.aliyuncs.com";
        client = new Client(config);
    }

    /**
     * 发送短信
     * @param sn 设备序列号
     * @param name 联动名称
     * @param phoneNumbers 手机号码
     */
    public void send(String sn,String name,String phoneNumbers){
        String templateParam = JSONUtil.createObj()
                .set("sn",sn)
                .set("content",name)
                .toString();
        SendSmsRequest request = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setTemplateParam(templateParam)
                .setPhoneNumbers(phoneNumbers);
        try {
            SendSmsResponse response = client.sendSmsWithOptions(request,new RuntimeOptions());
            log.info("发送短信结果 - {}",JSONUtil.parseObj(response.getBody()));
        }catch (Exception exception){
            log.error("发送短信失败.",exception);
        }
    }

    @Value("${sms.access.key.id}")
    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    @Value("${sms.access.key.secret}")
    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    @Value("${sms.template.code}")
    public void setTemplateCode(String templateCode) {
        this.templateCode = templateCode;
    }
}
